package com.guan.mysolutionstudy;

import org.junit.Test;

/**
 * @ClassName ReplaceSpaces
 * @Author GuanCary
 * @Date 2020/5/12 18:28
 * @Version 1.0
 * 剑指offer：请实现一个函数，将一个字符串中的每个空格替换成“%20”。
 * 例如，当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
 **/
public class ReplaceSpaces {
    //方法一
    public StringBuffer method1(StringBuffer stringBuffer) {
        StringBuffer stringBufferTemp = new StringBuffer();
        for (int i = 0; i < stringBuffer.length(); i++) {
            char c = stringBuffer.charAt(i);
            //当发现为空格
            if (" ".equals(String.valueOf(c))) {
                // string.charAt(i)="%20";左边为char类型
                stringBufferTemp.append("%20");
            } else {
                stringBufferTemp.append(c);
            }
        }
        System.out.println(stringBufferTemp);
        return stringBufferTemp;
    }

    //方法二:调用API
    public StringBuffer method2(StringBuffer stringBuffer) {
        System.out.println(stringBuffer.toString().replaceAll("\\s", "%20"));
        return new StringBuffer();
    }

    @Test
    public void test1() {
        method1(new StringBuffer("We Are Happy"));
    }

    @Test
    public void test2() {
        method2(new StringBuffer("We Are Happy"));
    }
}